#include "cast_custom_tiling.h"
#include "kernel_operator.h"

constexpr int32_t BUFFER_NUM = 2;          // 每队列 tensor 数

class KernelCast {
public:
    __aicore__ inline KernelCast() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR z,
                                uint32_t totalLength, uint32_t tileNum)
    {
        blockLength = totalLength / AscendC::GetBlockNum();
        this->tileNum   = tileNum;
        tileLength = blockLength / tileNum / BUFFER_NUM;

        // 仅绑定 x / z
        xGm.SetGlobalBuffer((__gm__ half *)x + blockLength * AscendC::GetBlockIdx(),
                            blockLength);
        zGm.SetGlobalBuffer((__gm__ float *)z + blockLength * AscendC::GetBlockIdx(),
                            blockLength);

        pipe.InitBuffer(inQueueX,  BUFFER_NUM, tileLength * sizeof(half));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, tileLength * sizeof(float));
    }

    __aicore__ inline void Process()
    {
        int32_t loopCount = tileNum * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<half> xLocal = inQueueX.AllocTensor<half>();
        AscendC::DataCopy(xLocal, xGm[progress * tileLength], tileLength);
        inQueueX.EnQue(xLocal);
    }

    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<half>  xLocal = inQueueX.DeQue<half>();
        AscendC::LocalTensor<float>  zLocal = outQueueZ.AllocTensor<float>();

        AscendC::Cast(zLocal, xLocal, AscendC::RoundMode::CAST_NONE, tileLength);

        outQueueZ.EnQue<float>(zLocal);
        inQueueX.FreeTensor(xLocal);
    }

    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<float> zLocal = outQueueZ.DeQue<float>();
        AscendC::DataCopy(zGm[progress * tileLength], zLocal, tileLength);
        outQueueZ.FreeTensor(zLocal);
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN,  BUFFER_NUM> inQueueX;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::GlobalTensor<half> xGm;
    AscendC::GlobalTensor<float> zGm;

    uint32_t blockLength;
    uint32_t tileNum;
    uint32_t tileLength;
};

extern "C" __global__ __aicore__ void cast_custom(GM_ADDR x, GM_ADDR z,
                                                 CastCustomTilingData tiling)
{
    KernelCast op;
    op.Init(x, z, tiling.totalLength, tiling.tileNum);
    op.Process();
}